import React, { FC, useEffect, useState } from 'react'
import ProCard from '@ant-design/pro-card'
import { Button, Checkbox, Col, Drawer, Form, Row, Tooltip, Tag, message, Modal, Input } from 'antd'
import { getValidList, updateFunctionArg } from '@/services/functionArg'

const confirm = Modal.confirm
const FormItem = Form.Item
const { CheckableTag } = Tag

interface ArgValidConfigProps {
  argValid:any,
  argId:string,
  visible:boolean,
  onClose:any,
}

const ArgValidConfig: FC<ArgValidConfigProps> = (props) => {

  const [form] = Form.useForm()

  const {argValid,argId, visible, onClose } = props
  const [validList, setValidList] = useState<any>([])
  const [selectedTags, setSelectedTags] = useState<any>([])

  useEffect(() => {
    if (visible) {
      getValidList().then(res => {
        if (res.code === 10000) {
          setValidList(res.data)
          getInitVal(res.data);
        }
      })
    }
  }, [visible])

  const getInitVal = (data:any) => {
    const selectArr = [];
    for (const item of argValid) {
      const startIndex = item.indexOf('(');
      const endIndex = item.indexOf(')');
      const val = item.slice(startIndex + 1,endIndex);
      const name = item.slice(0,startIndex)
      const itemData = data.filter((val:any) => val.name === name)[0];
      console.info(val)
      const args = eval(itemData.args) || [];
      if (args.length > 0) {
        const obj:any = {};
        const valArr = val.split(',');
        obj.firstVal = valArr[0].slice(valArr[0].indexOf('=')+1,valArr[0].length);
        if (args.length > 1) {
          obj.endVal = valArr[1].slice(valArr[1].indexOf('=')+1,valArr[1].length);
        }
        itemData.initData = obj;
      }
      itemData.value = item;
      selectArr.push(itemData)
    }
    setSelectedTags(selectArr);
  }

  const submit = () => {
    const arr: any[] = [];
    selectedTags.map((val:any) => arr.push(val.value));
    updateFunctionArg({id:argId,valid:JSON.stringify(arr)}).then(res => {
      if (res.code === 10000) {
        message.success('验证修改成功！')
        onClose(false,'update');
      }
    })
  }

  const handleChange = (item: any, checked: any) => {
    const val = eval(item.args)
    confirm({
      title: checked ? (item.args ? '请输入' : '是否添加此验证?') : '是否删除此验证？',
      content: checked ? (item.args ? getContent(item) : '请确认') : '请确认',
      okText: '确定',
      cancelText: '取消',
      onOk(close) {
        form.validateFields().then(res => {

          if (checked) {
            item.value = item.name +'(' +(item.args ?(val.length >1? `max=${res.endVal},min=${res.firstVal}`:`value=${res.firstVal}`):'') +')'
          }

          const nextSelectedTags = checked ? [...selectedTags, item] : selectedTags.filter((t: any) => t.id !== item.id)
          setSelectedTags(nextSelectedTags)
          close()
        }).catch(err => {
          message.error('请输入验证的值，不可为空！');
        })
      }
    })
  }

  const getContent = (item: any) => {
    const val = eval(item.args)

    return (
      <Form form={form} initialValues={item.initData || {}}>
        <Input.Group compact>
        <FormItem rules={[{ required: true, message: '请输入' }]} name="firstVal">
        <Input type='number' style={{ width: 100, textAlign: 'center', borderRight: val.length > 1 ? 0 : '' }} placeholder="value"/>
        </FormItem>
        {val.length > 1 && (
          <>
            <Input
              style={{
                width: 30,
                borderLeft: 0,
                borderRight: 0,
                pointerEvents: 'none',
                backgroundColor: '#fff'
              }}
              placeholder="~"
              disabled
            />
            <FormItem rules={[{ required: true, message: '请输入' }]} name="endVal">
            <Input
              type='number'
              style={{
                width: 100,
                textAlign: 'center',
                borderLeft: 0
              }}
              placeholder="value"
            />
            </FormItem>
          </>)}
        </Input.Group>
      </Form>
    )
  }


  return (
    <Drawer
      title="添加参数"
      width={700}
      onClose={() => onClose(false,'close')}
      visible={visible}
      bodyStyle={{ paddingBottom: 80, backgroundColor: '#f0f2f5' }}
      footer={
        <div style={{
          textAlign: 'right'
        }}>
          <Button key="submit" onClick={submit} type="primary">
            保存
          </Button>
          <Button style={{ marginLeft: 10 }} onClick={() => onClose(false)}>
            关闭
          </Button>
        </div>
      }>
      <Form>
        <ProCard>
          <FormItem name="valid" rules={[{ required: true, message: '请选择' }]} label="数据格式验证">
            {validList.map((item: any) => (
              <CheckableTag
                key={item.id}
                checked={selectedTags.indexOf(item) > -1}
                onChange={checked => handleChange(item, checked)}
              >
                <Tooltip placement="top" title={item.comment}> {item.name} </Tooltip>
              </CheckableTag>
            ))}
          </FormItem>
        </ProCard>
        <ProCard style={{ marginTop: 30 }}>
          <FormItem name=" " label="业务数据验证">

          </FormItem>
        </ProCard>
      </Form>


    </Drawer>
  )
}

export default ArgValidConfig
